<template>
    <div class="merchant-list">
        <el-card class="mb-4">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                <el-form-item label="报修标题">
                    <el-input v-model="searchForm.title" placeholder="请输入报修标题" clearable class="w-60" />
                </el-form-item>
                <el-form-item label="处理人姓名">
                    <el-input v-model="searchForm.handlerName" placeholder="请输入处理人姓名" clearable class="w-60" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select filterable  v-model="searchForm.status" clearable placeholder="请选择状态">
                        <el-option label="未处理" :value="0"></el-option>
                        <el-option label="处理中" :value="1"></el-option>
                        <el-option label="已处理" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="处理时间">
                        <el-date-picker v-model="searchForm.effectDate" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期" type="daterange" value-format="yyyy-MM-dd" class="w-full">
                        </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                    <el-button type="primary" @click="handleAdd" style="margin-left: 30px"
                        v-has="'repair:save'">新增报修</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    
        <!-- 表格 -->
        <el-table v-loading="loading" :data="tableData" border style="width: 100%;margin-top:15px">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="merchantName" label="商家名称" />
            <el-table-column prop="title" label="反馈标题" />
            <el-table-column prop="content" label="反馈内容" />
            <el-table-column prop="images" label="反馈图片" width="120">
                <template #default="{ row }">
                    <el-image v-if="row.images" style="width: 80px; height: 80px" :src="row.images"
                        :preview-src-list="[row.images]" fit="cover" />
                </template>
            </el-table-column>
            <el-table-column prop="feedbackType" label="反馈类型" width="120">
                <template #default="{ row }">
                    <el-tag v-if="row.feedbackType === 1" type="danger">产品问题</el-tag>
                    <el-tag v-if="row.feedbackType === 2" type="warning">服务问题</el-tag>
                    <el-tag v-if="row.feedbackType === 3" type="success">建议</el-tag>
                    <el-tag v-if="row.feedbackType === 4" type="info">其他</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="feedbackStatus" label="反馈状态" width="120">
                <template #default="{ row }">
                    <el-tag v-if="row.feedbackStatus === 0" type="danger">未处理</el-tag>
                    <el-tag v-if="row.feedbackStatus === 1" type="warning">处理中</el-tag>
                    <el-tag v-if="row.feedbackStatus === 2" type="success">已解决</el-tag>
                    <el-tag v-if="row.feedbackStatus === 3" type="info">已关闭</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="priority" label="优先级" width="120">
                <template #default="{ row }">
                    <el-tag v-if="row.priority === 1" type="danger">低</el-tag>
                    <el-tag v-if="row.priority === 2" type="warning">中</el-tag>
                    <el-tag v-if="row.priority === 3" type="success">高</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
                <template #default="{ row }">
                    <el-button type="text" v-has="'repair:update'" @click="handleEdit(row)">编辑</el-button>
                    <el-button type="text" style="color: #f56c6c" v-has="'repair:delete'"
                        @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    
        <!-- 分页 -->
        <div class="pagination">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next" :total="total">
            </el-pagination>
        </div>
    
        <!-- 新增/编辑弹窗 -->
        <el-dialog :close-on-click-modal="false"  :title="dialogType === 'add' ? '新增' : '编辑'" :visible.sync="dialogVisible" width="80%"
            @close="resetForm">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="dialog_height">
                <el-form-item label="商户" prop="merchantId">
                    <el-select filterable  v-model="form.merchantId" placeholder="请选择商户" style="width: 100%">
                        <el-option :label="item.name" :value="item.id" v-for="item,index in merchantList" :key="index" />
                    </el-select>
                </el-form-item>
                <el-form-item label="反馈标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入反馈标题" />
                </el-form-item>
                <el-form-item label="反馈内容" prop="content">
                    <el-input type="textarea" v-model="form.content" placeholder="请输入反馈内容" :rows="3" />
                </el-form-item>
                <el-form-item label="商家图片" prop="images">
                    <el-upload class="image-uploader" :headers="headers" :action="$uploadUrl" :show-file-list="false"
                        :on-success="handleUploadSuccess" :before-upload="beforeUpload">
                        <img v-if="form.images" :src="form.images" class="uploaded-image" />
                        <div v-else class="upload-placeholder">
                            <i class="el-icon-plus"></i>
                            <div class="upload-text">点击上传商家图片</div>
                        </div>
                    </el-upload>
                    <!-- <div class="form-tip">建议尺寸：200x200px，支持jpg、png格式</div> -->
                </el-form-item>
                <el-form-item label="反馈类型" prop="feedbackType">
                    <el-select filterable  v-model="form.feedbackType" placeholder="请选择反馈类型">
                        <el-option label="产品问题" :value="1"></el-option>
                        <el-option label="服务问题" :value="2"></el-option>
                        <el-option label="建议" :value="3"></el-option>
                        <el-option label="其他" :value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="反馈状态" prop="feedbackStatus">
                    <el-select filterable  v-model="form.feedbackStatus" placeholder="请选择反馈状态">
                        <el-option label="未处理" :value="0"></el-option>
                        <el-option label="处理中" :value="1"></el-option>
                        <el-option label="已解决" :value="2"></el-option>
                        <el-option label="已关闭" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="优先级" prop="priority">
                    <el-select filterable  v-model="form.priority" placeholder="请选择优先级">
                        <el-option label="低" :value="1"></el-option>
                        <el-option label="中" :value="2"></el-option>
                        <el-option label="高" :value="3"></el-option>
                    </el-select>
                </el-form-item>
    
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'MerchantList',
  data() {
    return {
      headers: {
        'token': localStorage.getItem('token')
      },
      // 搜索表单
      searchForm: {
        title: '',
        handlerName: '',
        status: '',
        effectDate: []
      },
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 表格数据
      tableData: [],
      loading: false,
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      uploadUrl: '', // 上传地址
      form: {
        merchantId: '',
        title: '',
        content: '',
        images: '',
        feedbackType: '',
        feedbackStatus: '',
        priority: ''
      },
      // 表单校验规则
      rules: {
        merchantId: [{ required: true, message: '请选择商户', trigger: 'blur' }],
        title: [{ required: true, message: '请输入反馈标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入反馈内容', trigger: 'blur' }],
        feedbackType: [{ required: true, message: '请选择反馈类型', trigger: 'blur' }],
        feedbackStatus: [{ required: true, message: '请选择反馈状态', trigger: 'blur' }],
        priority: [{ required: true, message: '请选择优先级', trigger: 'blur' }],
        images: [{ required: true, message: '请上传反馈图片', trigger: 'blur' }]
      },
      merchantList: []
    }
  },
  created() {
    this.getList();

  },
  methods: {
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const condition = {
          ...this.searchForm,
          startHandleTime: this.searchForm.effectDate[0] || '',
          endHandleTime: this.searchForm.effectDate[1] || ''
        }
        if (this.searchForm.effectDate) {
            delete condition.effectDate
        }
        const { data } = await this.$api.getRepairList({
          page: this.currentPage,
          size: this.pageSize,
          condition
        })
        this.tableData = data.result.records
        this.total = data.result.total
      } catch (error) {
        console.error('获取商家列表失败：', error)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        title: '',
        phone: ''
      }
      this.handleSearch()
    },

    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 新增
    handleAdd() {
      this.dialogType = 'add'
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit'
      this.form = { ...row }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该意见吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.deleteMerchantView(row.id)
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          console.error('删除失败：', error)
        }
      }).catch(() => { })
    },

    // 上传相关
    handleUploadSuccess(res) {
      this.form.images = res.result.filePath

    },

    beforeUpload(rawFile) {
      const imgSize = rawFile.size / 1024 / 1024 < 10
      const imgType = ['image/jpeg', 'image/png', 'image/gif']
      if (!imgType.includes(rawFile.type))
        message.notifyWarning('上传图片不符合所需的格式！')
      if (!imgSize) message.notifyWarning(`上传图片大小不能超过 10M！`)
      return imgType.includes(rawFile.type) && imgSize
    },

    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.dialogType === 'add') {
              await this.$api.addMerchantView(this.form)
              this.$message.success('新增成功')
            } else {
              await this.$api.editMerchantView(this.form)
              this.$message.success('编辑成功')
            }
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error(this.dialogType === 'add' ? '新增失败：' : '编辑失败：', error)
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      this.form = {
        name: '',
        title: '',
        imageUrl: '',
        address: '',
        phone: '',
        description: ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
.dialog_height{
    // height: 50vh;
    // overflow: hidden;
    // overflow-y: auto;
}
.image-uploader {
    .uploaded-image {
        width: 140px;
        height: 140px;
        object-fit: cover;
        border-radius: 4px;
    }

    .upload-placeholder {
        width: 140px;
        height: 140px;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        transition: border-color 0.3s;

        &:hover {
            border-color: #409EFF;
        }

        .el-icon-plus {
            font-size: 28px;
            color: #8c939d;
        }

        .upload-text {
            font-size: 12px;
            color: #8c939d;
            margin-top: 8px;
        }
    }
}

.merchant-list {
    padding: 20px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
}
</style>